/* 渲染进程 */
/* eslint-disable no-undef */
const fs = require("fs");

// 引入主进程中的窗口对象
const { ipcRenderer, remote } = require('electron');

document.title = "无标题";
// 获取文本框dom
let textAreaDom = document.querySelector("#text-area");

/**
 * 判断文件是否保存
 */
let isSave = true;
/**
 * 当前文件保存路径
 */
let currentFile = "";
/**
 * 编辑器插件对象
 */
let editor = null;
/**
 * META 初始化
 */
let META = {
    html: {
        init: () => {
            editor.setOption("mode", {
                name: "htmlmixed",
                scriptTypes: [{
                    matches: /\/x-handlebars-template|\/x-mustache/i,
                    mode: null
                },
                {
                    matches: /(text|application)\/(x-)?vb(a|script)/i,
                    mode: "vbscript"
                }]
            });
            editor.setOption("selectionPointer", true);
        }
    },
    jsp: {
        init: ()=> {
            editor.setOption("mode", "application/x-jsp");
            editor.setOption("lineNumbers", true);
            editor.setOption("indentUnit", 4);
            editor.setOption("indentWithTabs", true);
        }
    },
    js: {
        init: ()=> {
            editor.setOption("mode", ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"]);
            editor.setOption("lineNumbers", true);
            editor.setOption("indentUnit", 4);
            editor.setOption("indentWithTabs", true);
        }
    },
    asp: {
        init: ()=> {
            editor.setOption("mode", "application/x-aspx");
            editor.setOption("lineNumbers", true);
            editor.setOption("indentUnit", 4);
            editor.setOption("indentWithTabs", true);
        }
    },
    java: {
        init: ()=> {
            editor.setOption("mode", "text/x-java");
            editor.setOption("lineNumbers", true);
            editor.setOption("indentUnit", 4);
            editor.setOption("indentWithTabs", true);
            editor.setOption("matchBrackets", true);
        }
    },
    json: {
        init: ()=> {
            editor.setOption("mode", ["application/json", "application/x-json"]);
            editor.setOption("lineNumbers", true);
            editor.setOption("indentUnit", 4);
            editor.setOption("indentWithTabs", true);
        }
    },
    properties: {
        init: ()=> {
            editor.setOption("mode", "text/x-properties");
            editor.setOption("lineNumbers", true);
            editor.setOption("indentUnit", 0);
            editor.setOption("indentWithTabs", false);
        }
    },
    txt: {
        init: ()=> {
            editor.setOption("mode", "text/plain");
            editor.setOption("lineNumbers", true);
            editor.setOption("indentUnit", 4);
            editor.setOption("indentWithTabs", true);
        }
    }
};

window.onload = () => {
    // 初始化在线编辑器插件
    editor = CodeMirror.fromTextArea(textAreaDom);
    META.txt.init();

    // 内容变化的时候 让isSave等于false
    // textAreaDom.oninput = () => {
    //     if (isSave) {
    //         document.title += " *";
    //     }
    //     isSave = false;
    // }
    editor.on("inputRead", () => {
        if (isSave) {
            document.title += " *";
        }
        isSave = false;
    });

    // 页面右键监听
    window.addEventListener('contextmenu', (e) => {
        e.preventDefault();
        // 发送消息给主进程用于弹出右键快捷菜单
        ipcRenderer.send("showContextMenu");
    }, false);
}

// 监听主进程操作
ipcRenderer.on("action", (event, data) => {
    switch (data) {
        case "new":
            // 判断文件是否保存，如果没有保存，给出提示，并保存
            askSaveDialog();

            // textAreaDom.value = "";
            editor.setValue("");
            currentFile = "";
            document.title = "无标题";
            break;
        case "open":
            // 判断文件是否保存，如果没有保存，给出提示，并保存
            askSaveDialog();

            // 通过dialog打开文件
            remote.dialog.showOpenDialog({
                title: "打开",
                properties: ["openFile"],
                filters: [
                    // { name: '文本文件', extensions: ['txt', 'md', 'ini', 'html', 'js', 'css', 'java', 'json', 'yml', 'xml'] }
                    { name: '文本文件', extensions: ['*'] }
                ]
            }).then((result) => {
                if (!result.canceled) {
                    let dir = result.filePaths[0];
                    let data = fs.readFileSync(dir);
                    // 保存当前路径
                    currentFile = dir;
                    document.title = dir;
                    // textAreaDom.innerHTML = data;
                    // 初始化编辑器参数
                    initEditorOption(dir.substring(dir.lastIndexOf('.') + 1));
                    editor.setValue(data.toString());
                    editor.refresh();
                }
            }).catch((err) => {
                console.log(err);
            });
            break;
        case "save":
            saveCurrentDoc();
            break;
        case "close":
            askSaveDialog();
            // 通知主进程退出应用
            ipcRenderer.send('exit-app', "close");
            break;
        case "quit":
            askSaveDialog();
            // 通知主进程退出应用
            ipcRenderer.send('exit-app', "quit");
            break;
        default:
            break;
    }
});
/**
 * 初始化编辑器参数
 * @param {*} ext 
 */
function initEditorOption(ext) {
    switch (ext) {
        case "txt":
        case "text":
        case "conf":
        case "def":
        case "list":
        case "log":
            META.txt.init();
            break;
        case "jsp":
            META.jsp.init();
            break;
        case "js":
            META.js.init();
            // https://github.com/codemirror/CodeMirror/blob/master/mode/meta.js
            break;
        case "html":
            META.html.init();
            break;
        case "java":
            META.java.init();
            break;
        case "json":
        case "map":
            META.json.init();
            break;
        default:
            break;
    }
}
/**
 * 判断文件是否保存，如果没有保存，给出提示，并保存
 */
function askSaveDialog() {
    if (!isSave) {
        // 同步弹窗
        var result = remote.dialog.showMessageBoxSync({
            title: "提示",
            type: "question",
            message: "是否要保存此文件?",
            buttons: ["Yes", "No"]
        });
        if (result == 0) {
            saveCurrentDoc();
        } else {
            // 不保存 isSave = true
            isSave = true;
        }
    }
}
/**
 * 执行保存的方法
 */
function saveCurrentDoc() {
    if (!currentFile) {
        var result = remote.dialog.showSaveDialogSync({
            title: "保存",
            defaultPath: "voishion.txt",
            filters: [
                { name: '文本文件', extensions: ['*'] }
            ]
        });
        if (result) {
            currentFile = result;
            // fs.writeFileSync(currentFile, textAreaDom.value);
            fs.writeFileSync(currentFile, editor.getValue());
            isSave = true;
            document.title = currentFile;
        }
    } else {
        // fs.writeFileSync(currentFile, textAreaDom.value);
        fs.writeFileSync(currentFile, editor.getValue());
        isSave = true;
        document.title = currentFile;
    }
}